﻿namespace Universe.MySqlTests
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.Text;

    using NUnit.Framework;

    public class BaseTest
    {
        private static Stopwatch StartAt = Stopwatch.StartNew();
        [TestFixtureSetUp]
        public void TestFixtureSetUp()
        {
            CrossInfo.AttachUnitTrace("MySQL Tests");
            StartAt = Stopwatch.StartNew();

            var mysqls = CrossInfo.GetProcessInfoByName("mysqld");
            var mysqlInfo = string.Join(", ", mysqls.Select(x => string.Format("{0:n0}Mb/{1:n0}Mb", x.Rss / 1024L, x.Vsz / 1024L)));
            Trace.WriteLine("MySql: " + mysqlInfo);

        }

        Stopwatch TestAt = Stopwatch.StartNew();
        [SetUp]
        public void SetUp()
        {
            TestAt = Stopwatch.StartNew();
            CrossInfo.NextTest();
        }

        [TearDown]
        public void TearDown()
        {
            // Trace.WriteLine(Environment.StackTrace + Environment.NewLine);
            if (true || CrossInfo.ThePlatform == CrossInfo.Platform.MacOSX || CrossInfo.ThePlatform == CrossInfo.Platform.Linux)
            {
                var ws1 = (Process.GetCurrentProcess().WorkingSet64 / 1024L / 1024).ToString("n0");
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                var ws2 = (Process.GetCurrentProcess().WorkingSet64 / 1024L / 1024).ToString("n0");
                var mysqls = CrossInfo.GetProcessInfoByName("mysqld");
                var mysqlInfo = string.Join(", ", mysqls.Select(x => string.Format("{0:n0}Mb/{1:n0}Mb", x.Rss / 1024L, x.Vsz / 1024L)));
                Trace.WriteLine("***** " + TestAt.Elapsed + ", "
                    + "Working Set: " + ws1 + " Mb"
                    + (ws1 != ws2 ? ", after GC: " + ws2 + " Mb" : "")
                    + (mysqls.Count > 0 ? ", mysqld " + mysqlInfo : "")
                    + Environment.NewLine);
            }
        }


        [TestFixtureTearDown]
        public void TestFixtureTearDown()
        {
            AppDomain.CurrentDomain.DomainUnload += (sender, args) =>
            {
            };

            Trace.WriteLine("Total time: " + StartAt.Elapsed);
        }

    }
}